import json, uuid
from datetime import datetime, date
from flask import Flask, Response, request, Blueprint, jsonify
from flask_jwt_extended import JWTManager, create_access_token, jwt_required, get_jwt_identity
from sqlalchemy import func, select, exc, and_, distinct, literal, text, insert
from app.common.commonMessage import CommonMassages
from app.config.db import DBUtils
from app.config.jsonEncoder import CustomJSONEncoder
from app.service.OpponentCharactersService_Pandas import OpponentCharactersServicePandas
from app.service.tradeCrowdService import TradeCrowdService
from app.service.industryFlowService import IndustryFlowService
from app.service.belongingFlowService import BelongingFlowService
from app.service.controllerFlowService import ControllerFlowService
from app.service.capitalRiskService import CapitalRiskService
from app.service.transactionFeaturesService import TransactionFeatures
from app.model.BusinessInfoModel import BusinessInfo
from app.model.CalculationModel import CalcuResult
app = Flask(__name__)
# 创建蓝图
calcu_result = Blueprint('calcu_result', __name__, url_prefix='/kshx')
# 服务
trade = TradeCrowdService()
industry = IndustryFlowService()
belong = BelongingFlowService()
controller = ControllerFlowService()
opponent = OpponentCharactersServicePandas()
capital = CapitalRiskService()
transaction = TransactionFeatures()

# 获取session
db_utils = DBUtils()
session = db_utils.get_session()

@calcu_result.route('/calcu', methods=['GET'])
# @jwt_required()
def calcu():
    all_results = []
    for i in [2024,2025]:
        start = date(i, 1, 1).strftime('%Y-%m-%d')
        end = date(i, 12, 31).strftime('%Y-%m-%d')

        query = select(BusinessInfo.GSMC, BusinessInfo.IS_CYDW, BusinessInfo.BH).where(BusinessInfo.GSMC == "中国电子科技集团有限公司")
        gs_list = session.execute(query).mappings()

        for row in gs_list:
            try:
                gsmc, is_cydw, dwbh = row['GSMC'], row['IS_CYDW'], row['BH']
                rs_trade = trade.select_trade_crowd_info(session, gsmc, is_cydw, start, end)
                rs_industry = industry.select_industry_flow_info(session, gsmc, is_cydw, i)
                rs_belong = belong.select_belonging_flow_info(session, gsmc, is_cydw, i)
                rs_controller = controller.select_controller_flow_info(session, gsmc, is_cydw, i)

                data1 = opponent.select_dstz_data(session, gsmc, is_cydw, start, end)
                data2 = opponent.select_dsgm_cydw_data(session, gsmc, is_cydw, start, end)
                data3 = opponent.select_dyfb_data(session, gsmc, is_cydw, start, end)
                data4 = opponent.select_hyfb_data(session, gsmc, is_cydw, start, end)

                rs_opponent = {
                    'max_info': data1,
                    'dsgm_cydw': data2,
                    'dyfb': data3,
                    'hyfb': data4
                }

                rs_capital = capital.select_capital_risk(session, gsmc, i, is_cydw)
                rs_transaction = transaction.select_trading_indicators_data(session, gsmc, is_cydw, i)

                insert_all = [
                    ('cd', rs_trade),
                    ('industry', rs_industry),
                    ('belonging', rs_belong),
                    ('controller', rs_controller),
                    ('ot', rs_opponent),
                    ('cl', rs_capital),
                    ('tn', rs_transaction)
                ]

                for code, data in insert_all:
                    all_results.append(CalcuResult(
                        ID=uuid.uuid4().hex,
                        GSMC=gsmc,
                        JSONDATA=json.dumps(data, cls=CustomJSONEncoder),
                        TYPE=code,
                        JYND=i,
                        DWBH=dwbh
                    ))
            except Exception as e:
                session.rollback()
                print(f"[ERROR] 处理失败: {row['GSMC']} 年份：{i}，错误：{e}")

    session.add_all(all_results)
    session.commit()
    print('所有数据插入完成！')
    return jsonify({"code": 200, "message": "处理成功"})



